const sha1 = require('sha1');
const rawBody = require('raw-body');
const util = require('./util');

module.exports = function (config) {
    return main = async ctx => {
        let token = config.token;
        console.log(ctx.request);
        let signature = ctx.request.query.signature;
        let nonce = ctx.request.query.nonce;
        let timestamp = ctx.request.query.timestamp;
        let echostr = ctx.request.query.echostr;

        let str = [token, timestamp, nonce].sort().join('');
        let sha = sha1(str);
        if (ctx.request.method === 'GET') {
            ctx.response.body = (sha === signature) ? echostr + '' : 'failed';  //比较并返回结果
        } else if (ctx.request.method === 'POST') {
            let data = await rawBody(ctx.req, { length: ctx.request.length, limit: '1mb', encoding: ctx.request.charset });

            let content = await util.parseXMLAsync(data);
            console.log('content', content);

            let message = util.formatMessage(content.xml);

            console.log('message', message);
            // var content = yield util.parseXMLAsync(data);   //xml数据解析成xml对象

            // var message = util.formatMessage(content.xml);

            // this.weixin = message;  //挂载消息

            // yield handler.call(this, next);   //转到外层逻辑

            // wechat.replay.call(this);  //真正回复
        }
    };
}

